<template>
   
  <el-main>

      <!-- 查询条件 -->
      <el-form ref="searchForm" label-width="80px" :inline="true" size="small">
        <el-form-item>
          <el-input v-model="searchModel.description" placeholder="请输入图片描述"/>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchModel.tags" placeholder="请选择图片标签">
              <el-option
                v-for="item in tagsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
          <el-button icon="el-icon-refresh-right" @click="resetValue()">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="12" >
        <el-col :span="6" v-for="(picture, index) in pictureList" :key="index"  >
          <el-card :body-style="{ padding: '0px' }" :ref="'cardRef'+index" style="margin-top: 10px;" >
              <i class="el-icon-delete-solid imageIcon" @click="showDeleteImageDialog(picture)" v-show="deleteImageIconDisplay[index].value"></i>
              <el-tooltip 
               class="item"
               effect="dark" 
               :content="picture.description" 
               open-delay="1000"
               placement="top">
                <el-image 
                  :src="picture.url" 
                  class="image" 
                  style="width: 100%;
                  height: 180px;" 
                  :preview-src-list="pictureUrls"
                  :initial-index = "index"
                  @mouseenter="showDeleteImageIcon(index)"
                  @mouseleave="removeDeleteImageIcon(index)" 
                  >
                </el-image>
              </el-tooltip>
         
              <div style="padding: 14px;" class="add_advice"  >
                <el-tag  v-for="(tag,index) in picture.param.tags" :key="index"
                  size="mini"
                  @close="handleCloseTag(tag,picture)"
                  :effect="tag.effect"
                  :type="tag.type" 
                  :color="tag.color"
                  :style="{'border-color': tag.borderColor,'background-color':tag.bgColor, 'color':tag.color}" 
                  >{{ tag.name }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-show="false"
                  v-model="inputValue[index].value"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(index,picture)"
                  @blur="handleInputConfirm(index,picture)"
                >
                </el-input>
                <el-button 
                icon="el-icon-edit"
                size="mini" 
                @click="becomeEditMode(picture,index)" 
                class="operationTag"
                round>
              </el-button>
              </div>
          </el-card>
        </el-col>
      </el-row>

    <!-- 分页工具栏 -->
    <div class="paginationClass">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[12, 24, 36, 48, 60]"
        :page-size="12"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        >
    </el-pagination>
    </div>
  
  </el-main>

</template>

<script>
import pictureApi from '@/api/picture/picture';
import plateApi from '@/api/picture/plate';
//导入token
import {getToken} from '@/utils/auth'
//导入tag.js脚本
import tagApi from '@/api/picture/tag';

const tagdoms = document.getElementsByClassName('input-new-tag');

export default {
  name: "picture-display",
  data() {
    return {
       searchModel :{
           creatorId: this.$store.getters.userId , //当前登录用户id, 
           plateId: '',
           description : '',  //图片描述
           tags : '' , //标签分类
           pageNo: 1, //当前页码
           pageSize: 12, //每页显示数量
        },
        pageNo: 1, //当前页码
        pageSize: 12, //每页显示数量
        total: 0, //总数量
        pictureList:[],
        pictureUrls:[],
          
        uploadHeader:{  
          "Authorization" : getToken()  //上传需要携带的数据
        },

        pictureObject:{
          id: '', 
          plateId: '',
          name: '',
          url: '',
          tags: '',
          description: '',
          creatorId: this.$store.getters.userId, //会被清除
        },
        tagList: [], //标签选项
        inputValue: [],

        deleteImageIconDisplay : [] , //删除图标是否展示

        tagsOptions:[],  //标签集合
     
    };
  },
  methods : {
     //鼠标移入到图片内,展示删除图标
     showDeleteImageIcon(index){
       this.deleteImageIconDisplay[index].value = true;
     },
    //鼠标移出到图片外,不展示图标
     removeDeleteImageIcon(index){
       this.deleteImageIconDisplay[index].value = false;
     },

    //删除图标弹出框事件
     showDeleteImageDialog(picture){
        this.$confirm('此操作将永久删除<span style="color:red">《'+ picture.name +'》</span>,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
        }).then(() => {
            return pictureApi.deletePictureApi({id:picture.id}); 
        }).
        then((res)=>{
          if(res.success){
                this.$message({type: 'success',message: '删除成功!'});
                this.search(); 
            }else{
                this.$message({type: 'error',message: '删除失败!'});
            } 
        }).
        catch(() => {
              this.$message({type: 'success',message: '已取消删除'});          
        });
    }, 
     handleCloseTag(tag,picture) {
        let tags = picture.param.tags;
        //删除picture中的tag
        tags.splice(tags.indexOf(tag), 1);
        //发送更新请求
        this.editTags(picture,{'newTagName' : ''});
      },
      handleInputConfirm(index,picture) {
        let tags =  picture.param.tags 
        let tagValue = this.inputValue[index].value;
        if(tagValue.length > 2 ){
            this.$message.warning("关键字长度不能超过于3"); 
        }else if(tagValue.replace(/\s+/g, '') == ""  ){
            this.$message.warning("关键字长度不能为0"); 
        }else{
          //往tags插入新的tag
          tags.push({'name':tagValue}); 
          console.log("tags-->"+JSON.stringify(tags))
          //重新添加x
          this.addXforTag(index);
          this.editTags(picture,{'newTagName' : tagValue});
     
        }
        tagdoms[index].setAttribute("style","display:none")
        this.inputValue[index].value = '';

      },
      //当失去焦点 tag的叉叉消失
      editTags(picture,Obj) {
        let tagsStr = "";
        let tags = picture.param.tags ;
        for(let index in tags){
          tagsStr += tags[index].id + ","
        }
        let res =  pictureApi.editPictureTag(picture.id,tagsStr,Obj);
        if(res.success){
          this.$message.success("编辑标签成功")
        }
      },
    
       async search(){
            let plateName = this.$route.name;
            await  plateApi.getPlateIdByName(plateName)
              .then((response) => {
                  if (response.code == 200) {
                        this.searchModel.plateId = response.data;
                        this.searchModel.pageNo = this.pageNo;//当前页码
                        this.searchModel.pageSize = this.pageSize;//每页显示数量
                        let res =  pictureApi.list(this.searchModel);
                        new Promise((resolve, reject) =>{
                            setTimeout(() =>{
                               //成功的时候调用resolve
                               resolve(res);
                            }, 1000)
                        }).then((data) =>{
                            //处理成功后的逻辑
                            //这个data 是接收的resolve参数
                            if(data.success){
                              this.pictureList = data.data.records;
                              for(let index in this.pictureList){
                                 this.pictureUrls.push(this.pictureList[index].url)
                                 //输入框赋值
                                 this.inputValue.push({value: ''})
                                 //给删除图片的图标赋值
                                 this.deleteImageIconDisplay.push({value: false})
                              }
                              //总数量
                              this.total = data.data.total;
                          }
                        }).catch((err) =>{
                            console.log(err);
                        })
                       
                  }
            })
            .catch((e) => {
              this.$message.error("获取图片失败");
              console.log(e)
            });
       },
        /**
        * 重置查询条件
        */
        resetValue() {
          this.searchModel.description =  "";
          this.searchModel.tags =  "";
        },
        /**
        * 当每页数量发生变化时触发该事件
        */
        handleSizeChange(size) {
            this.pageSize = size ;
            this.search();
        },
        /**
        * 当页码发生变化时触发该事件
        */
        handleCurrentChange(page) {
            this.pageNo = page ;
            this.search();
        }, 
        /**
        * 为 tag 加 x
        */
       addXforTag(index){
          let components = this.$refs['cardRef'+`${index}`][0].$children;
          for(let i in components){
                  //判断是否是el-tag标签
                  let isElTage = components[i].$el.className.indexOf("el-tag");
                  //为每一个tag添加一个叉叉 除了操作tag
                  if(isElTage != -1 ){
                    components[i].closable = true ;
                  }
          }
       },

         /**
          *  变为编辑模式
          */
          async becomeEditMode(item,index) { 
              //为已经存在的tag添加x
              this.addXforTag(index);
              //清空当前输入框的数据
              let tags = item.param.tags;
              if(tags.length <= 3){
                tagdoms[index].setAttribute("style","display:true")
              }
              this.$resetForm("pictureForm",this.pictureObject);  //清空表单数据 
              this.pictureObject.creatorId = this.$store.getters.userId //当前登录用户id
              let res = await tagApi.list({'userId': this.pictureObject.creatorId})
              if(res.success){
                this.tagList = res.data;
                this.pictureObject.plateId = item.id ; //设置图片分区id
                this.pictureObject.name = item.name ; //设置图片名字
                this.pictureObject.url = item.url ;   //设置图片
                this.pictureObject.tags = item.param.tags   //设置标签
                this.pictureObject.description = item.description; //设置描述
              }else{
                this.$message.error('加载标签失败');
              }
          
        },
        /**
          * 窗口取消事件
          */
          onClose() {
              this.pictureDialog.visible = false
          },
          /**
          * 窗口确认事件
          */
          onConfirm() {
            
              //表单验证
              this.$refs.pictureForm.validate(async (valid)=>{
              if(valid){
                  //设置tags
                  let options = this.$refs.optionRef.selected
                  this.pictureObject.tags = '';
                  for(let index in options){
                      this.pictureObject.tags += options[index].value + ",";
                  }
                  //设置urls
                  if(this.fileObject.length === 0){
                    this.$message.error("请至少上传一张图片");
                    return;
                   }
                  let res = null;
                  this.pictureObject.url = '';
                  for(let index in this.fileObject){
                      let obj  = this.fileObject[index];
                      if(obj.url != "" && obj.url != undefined){
                         this.pictureObject.url += obj.url +',';
                      }
                  }
                 
                  //发送修改请求
                  res = await pictureApi.updatePictureApi(this.pictureObject);
                  
                  //判断是否成功
                  if (res.success) {
                      this.$message.success(res.message);
                      //刷新
                      this.showPlates();
                      //关闭窗口
                      this.pictureDialog.visible = false;
                      //清空
                      this.fileObject = [];
                  } else {
                      this.$message.error(res.message);
                  }
              }
              });

          },   
         //获取所有标签
        async getAllTag(){
           let res = await tagApi.getAllTagApi();
           if(res.success){
               let tags = res.data;
               for(let index in tags){
                 this.tagsOptions.push({value:tags[index].id,label:tags[index].name});   
               }
           }else{
              this.$message.error(res.message);
           }

        },

      
  },
  created(){
    this.getAllTag();
    this.search(); 
  }

}
</script>

<style lang="scss" >
 
  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
      display: table;
      content: "";
  }
  
  .clearfix:after {
      clear: both
  }
  .el-tag{
    margin-left: 4px;
  }
  .paginationClass {
    position: fixed;
    bottom: 0;
    height: 40px;
    width: 100%;
}
.operationTag:hover{
   background-color: #FFFFFF;
   border-color: #e73acd;
   color: #e73acd;
   cursor:pointer;
}
.operationTag{
   margin-left: 8px;
   width: 35px;
   height: 20px;
   vertical-align: middle;

   color: #FFFFFF;
   border-color: #0bdbb5;
   background-color: #0bdbb5;

   i.el-icon-edit{
      position: absolute;
      // margin-top: -5px;
      margin: -5px 0px 0px -5px;
      padding: auto;
  }
}


.input-new-tag {
      width: 40px;
      height: 20px;
      vertical-align: middle;
      .el-input__inner{
      width: 40px;
      height: 20px;
      margin: 0px 0px 0px 4px;
      padding: 0px 5px;
  }
}
  
.imageIcon{
      font-size: 20px;
      color: hsl(343, 90%, 45%);
      margin-left: 22%;
      margin-top: 5px;
      background-color: transparent;
      border: none;
      position: absolute;
      z-index: 100;
}  
</style>